package net.liteheaven.xblib.common.convert;

import java.text.DecimalFormat;

public class FileSizeUtil {
	
	private static final int MB_2_BYTE = 1024 * 1024;
	private static final int KB_2_BYTE = 1024;
	private static final DecimalFormat DOUBLE_DECIMAL_FORMAT = new DecimalFormat("0.##");
	
	public static CharSequence getFileSizeText(long size) {
		if (size <= 0) {
			return "0M";
		}

		if (size >= MB_2_BYTE) {
			return new StringBuilder(16).append(
					(DOUBLE_DECIMAL_FORMAT).format((double) size
							/ MB_2_BYTE)).append("M");
		} else if (size >= KB_2_BYTE) {
			return new StringBuilder(16).append(
					(DOUBLE_DECIMAL_FORMAT).format((double) size
							/ KB_2_BYTE)).append("K");
		} else {
			return size + "B";
		}
	}

}
